package com.neusoft.ecommerce.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 
 * @author YinKuenTam
 *
 */
@RestController
public class UploadController {
	private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

	private final String path = UploadController.class.getResource("/").toString();
	/**
	 * 读取配置文件
	 */
	@Value("${image.upload.path}")
    private String imageUploadPath;
	private final String getPath = getPath(path);

    public String getPath(String path) {
        path=path.substring(path.indexOf("/")+1);
        int index = 2;
        for (int i = 0; i <= index; i++){
            if (path.contains("/")) {
                path=path.substring(0,path.lastIndexOf("/"));
            }
        }
        return path;
    }

	@RequestMapping("/upload")
	@ResponseBody
	public Map<String, Object> upload(@RequestParam("file") MultipartFile file, Model model) {
    	String absolutePath = getPath + imageUploadPath;
		System.out.println(absolutePath);
		System.out.println(1);
		Map<String, Object> map = new HashMap<>(16);
    	if (file.isEmpty()) {
			map.put("code", "1");
			map.put("msg", "文件为空");
			return map;
		}
		String fileName = file.getOriginalFilename();
    	// 取出上传文件的后缀/类型
		String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
		// 随机生成一个新的文件名
		String uuid = UUID.randomUUID().toString();
		String newFileName = uuid + "." + extName;
		File dest = new File(absolutePath +"/"+ newFileName);
		logger.info("上传成功： " + dest.getAbsolutePath());
		try {
			file.transferTo(dest);
			model.addAttribute("imageFile", "images/"+newFileName);
			logger.info("上传成功");
			map.put("code", "0");
			map.put("msg", "上传成功");
			map.put("src", "images/" + newFileName);
		} catch (IOException e) {
			logger.error(e.toString(), e);
		}
		return map;
	}
}
